//
//  JGRootTableViewController.m
//  JGNumberKeyBoard
//
//  Created by 古俊杰 on 2017/6/5.
//  Copyright © 2017年 古俊杰. All rights reserved.
//

#import "JGRootTableViewController.h"
#import "NumKeyboard.h"
#import "KeyboardBottomBar.h"
#import "UIView+Category.h"

#define NumKeyboardheight (isPad ? 360 : 288)

@interface JGRootTableViewController () <UITextFieldDelegate,NumKeyboardDelegate,UISearchBarDelegate, UISearchDisplayDelegate>
{
     BOOL _isSearchNow;
}

@property (nonatomic, strong) UIView *intputBackView;
@property (nonatomic, strong) UITextField *intputTextFeild;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) KeyboardBottomBar *keyboardBottomBar;
@property (nonatomic, strong) NumKeyboard *numKeyboard;

@property (nonatomic, weak)UIButton *deleteBtn;


@end

@implementation JGRootTableViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(UIView *)intputBackView
{
    if (!_intputBackView) {
        self.intputBackView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height, self.view.width, 55)];
        self.intputBackView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.intputBackView];
    }
    return _intputBackView;
}

-(NumKeyboard *)numKeyboard
{
    if (!_numKeyboard) {
        self.numKeyboard = [[NumKeyboard alloc] init];
        self.numKeyboard.delegate = self;
        self.numKeyboard.frame = CGRectMake(0, Main_Screen_Height, Main_Screen_Width, NumKeyboardheight);
    }
    return _numKeyboard;
}

-(KeyboardBottomBar *)keyboardBottomBar
{
    if (!_keyboardBottomBar) {
        self.keyboardBottomBar = [KeyboardBottomBar instanceKeyboardBottomBar];
        self.keyboardBottomBar.frame = self.bottomView.bounds;
        [self.bottomView addSubview:self.keyboardBottomBar];
    }
    return _keyboardBottomBar;
}

//--底部操作条----没有和拨号键盘放在一起，因为键盘隐藏时，操作条还要在
-(UIView *)bottomView
{
    if (!_bottomView) {
        self.bottomView = [[UIView alloc] initWithFrame:(CGRect){{0,self.view.height - 50} , {self.view.width, 50}}];
        self.bottomView = self.bottomView;
        self.bottomView.backgroundColor = [UIColor whiteColor];
        self.bottomView.hidden = YES;
    }
    return _bottomView;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.bottomView removeFromSuperview];
    [[[UIApplication sharedApplication].windows lastObject] addSubview:self.bottomView];
    
    
    if (!_isSearchNow) {
        [self phoneNumViewShow:YES];
    }
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self phoneNumViewShow:NO];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.intputBackView.top = Main_Screen_Height;
    }];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //加载网络数据
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"拨号盘";
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    NSLog(@"%f",self.view.height);
    
    //初始化底部操作条
    
    
    //初始化拨号盘
    [self setupNumKeyboard];
    //监听键盘通知
    [self setupNoti];
    
}


#pragma mark -- 初始化拨号盘
- (void)setupNumKeyboard
{
    //输入框
    self.intputTextFeild = [[UITextField alloc] initWithFrame:CGRectMake(45, 0, self.view.width - 100, self.intputBackView.height)];
    self.intputTextFeild.textColor = RGB(50, 50, 50);
    self.intputTextFeild.adjustsFontSizeToFitWidth = YES;
    self.intputTextFeild.borderStyle = UITextBorderStyleNone;
    self.intputTextFeild.textAlignment = NSTextAlignmentCenter;
    self.intputTextFeild.font = [UIFont systemFontOfSize:32];
    self.intputTextFeild.delegate = self;
    [self.intputBackView addSubview:self.intputTextFeild];
    //删除按钮
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.hidden = YES;
    self.deleteBtn = deleteBtn;
    deleteBtn.frame = CGRectMake(self.view.width - 50, 8, 40, 40);
    [deleteBtn setImage:[UIImage imageNamed:@"U脉电话-删除"] forState:UIControlStateNormal];
    [deleteBtn addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.intputBackView addSubview:deleteBtn];
    //分割线
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.intputBackView.width, 1)];
    line.backgroundColor = RGB(240, 240, 240);
    [self.intputBackView addSubview:line];
    
    //底部操作View
    __weak typeof(self)weakSelf = self;
    self.keyboardBottomBar.gotoContact = ^()
    {
        //通讯录
//        weakSelf.hidesBottomBarWhenPushed = YES;
        //self.hidesBottomBarWhenPushed = NO;
        
    };
    
    self.keyboardBottomBar.videoCallAction = ^()
    {
        //视频呼叫  createVideoCallMeeting
//        weakSelf.hidesBottomBarWhenPushed = YES;
    };
    
    self.keyboardBottomBar.callAction = ^()
    {
        //拨打电话
        if (weakSelf.intputTextFeild.text.length >0)
        {
            
        } else
        {
            if (isPad) {
                [weakSelf showKeyboardWithDuration:0.25];
            } else {
                [weakSelf.intputTextFeild becomeFirstResponder];
            }
            weakSelf.keyboardBottomBar.keyBoardHidden = NO;
        }
        
    };
    self.keyboardBottomBar.showKeyboard = ^(BOOL isSelected)
    {
        //键盘隐藏
        if (isSelected)
        {
            if (weakSelf.intputTextFeild.text.length > 0) {
                weakSelf.keyboardBottomBar.phoneCallBtnHidden = NO;
            }
            if (isPad) {
                [weakSelf showKeyboardWithDuration:0.25];
            } else {
                [weakSelf.intputTextFeild becomeFirstResponder];
            }
        } else {
            if (isPad) {
                [weakSelf hideKeyboardWithDuration:0.25];
            } else {
                [weakSelf.intputTextFeild resignFirstResponder];
            }
            
        }
    };
    
    if (isPad)
    {
        self.intputTextFeild.enabled = NO;
        [self.view addSubview:self.numKeyboard];
        
    } else {
        self.intputTextFeild.inputAccessoryView = self.numKeyboard;
        self.intputTextFeild.inputView = [[UIView alloc] init];
        [self.intputTextFeild reloadInputViews];
        
    }
    
    
    
}

#pragma mark -- 监听键盘通知
- (void)setupNoti
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

// 设置输入条的位置（高度）
- (void)keyboardWillShow:(NSNotification *)note
{
    double keyboardTransitionDuration;
    [[note.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&keyboardTransitionDuration];
    //显示键盘
    [self showKeyboardWithDuration:keyboardTransitionDuration];
    
}
// 设置输入条的位置（高度）
- (void)keyboardWillHide:(NSNotification *)note
{
    double keyboardTransitionDuration;
    [[note.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&keyboardTransitionDuration];
    //隐藏键盘
    [self hideKeyboardWithDuration:keyboardTransitionDuration];
    
}

#pragma mark -- 拨号盘显示和隐藏
//显示
- (void)showKeyboardWithDuration:(double)keyboardTransitionDuration
{
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:keyboardTransitionDuration
                          delay:0.0f
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         
                         if (_isSearchNow)
                         {
                             weakSelf.intputBackView.top = Main_Screen_Height;
                             
                         } else
                         {
                             //                             NSLog(@"%f", Main_Screen_Height - NumKeyboardheight - weakSelf.intputBackView.height);
                             
                             if (isPad) {
                                 weakSelf.intputBackView.top = Main_Screen_Height - NumKeyboardheight - weakSelf.intputBackView.height;
                                 weakSelf.numKeyboard.top = weakSelf.intputBackView.bottom;
                                 
                             } else {
                                 weakSelf.intputBackView.top = Main_Screen_Height - 64 - NumKeyboardheight - weakSelf.intputBackView.height;
                             }
                             
                         }
                     }
                     completion:^(BOOL finished){
                         
                     }];
}

//隐藏
- (void)hideKeyboardWithDuration:(double)keyboardTransitionDuration
{
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:keyboardTransitionDuration
                          delay:0.0f
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         weakSelf.intputBackView.top = Main_Screen_Height;
                         if (isPad) {
                             weakSelf.numKeyboard.top = weakSelf.intputBackView.bottom;
                         }
                     }
                     completion:^(BOOL finished){
                         
                     }];
}


/**
 * 控制视图的显示
 */
- (void)phoneNumViewShow:(BOOL)show
{
    if (show)
    {
        if (isPad) {
            [self showKeyboardWithDuration:0.25];
        } else {
            [self.intputTextFeild becomeFirstResponder];
        }
        self.bottomView.hidden = NO;
        self.keyboardBottomBar.keyBoardHidden = NO;
        self.tableView.height = self.view.height - 50;
        
    } else {
        if (isPad) {
            [self hideKeyboardWithDuration:0.25];
        }
        self.bottomView.hidden = YES;
        self.tableView.height = self.view.height;
        self.intputTextFeild.text = nil;
    }
    
}

#pragma mark -- 监听输入框粘贴的文字----只能粘贴数字到输入框；
-(BOOL)canBecomeFirstResponder{
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    
    UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
    NSLog(@"*************%@",pasteboard.string);
    
    if (pasteboard.string.length > 0)
    {
        NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:pasteboard.string];
        NSMutableString *str = attributedString.string.mutableCopy;
        
        NSString *pasteboardNum = @"";
        
        //解析是否是数字
        for(int i =0; i < str.length; i++)
        {
            NSString *temoStr = [str substringWithRange:NSMakeRange(i, 1)];
            NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"^[0-9]*$"];
            if ([numberPre evaluateWithObject:temoStr])
            {
                pasteboardNum = [pasteboardNum stringByAppendingString:temoStr];
            }
        }
        
        NSLog(@"-------------%@",pasteboardNum);
    
        //        NSLog(@"%@",pasteboardNum);
        pasteboard.string = pasteboardNum;
        //如果不包含电话
        if ([pasteboardNum isEqualToString:@""]) {
            pasteboard.string = @" ";
        }
    }
    return [super canPerformAction:action withSender:sender];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return 0;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    
    [self hideNumberKeyBoardOnly];
    
}

#pragma mark -- 只是隐藏拨号盘
- (void)hideNumberKeyBoardOnly
{
    if (isPad) {
        [self hideKeyboardWithDuration:0.25];
    } else {
        [self.intputTextFeild resignFirstResponder];
    }
    self.keyboardBottomBar.keyBoardHidden = YES;
    self.keyboardBottomBar.phoneCallBtnHidden = YES;
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.25 animations:^{
        weakSelf.intputBackView.top = Main_Screen_Height;
    }];
}

#pragma mark -- 删除电话号码
- (void)deleteAction:(UIButton *)button
{
    if (isPad)
    {
        [self padClickedDeleteBtn];
        
    } else {
        self.numKeyboard.clickedDeleteBtn = YES;
    }
    
}

#pragma mark -- iPad中删除号码时
- (void)padClickedDeleteBtn
{
    NSString *tempString = self.intputTextFeild.text;
    if (tempString.length > 0)
    {
        NSString *newString = [tempString substringToIndex:tempString.length - 1];
        self.intputTextFeild.text = newString;
        if (newString.length == 0)
        {
            //清空了号码
#warning 刷新表格数据
            [self.tableView reloadData];
            
            self.deleteBtn.hidden = YES;
            
        } else
        {
            //减少号码
            //刷新数据
            [self reloadDataWithNumber:newString];
        }
    }
}

#pragma mark -- NumKeyboardDelegate
-(void)numKeyboardClicked:(NumKeyboard *)numKeyboard withKeyboardNumber:(NSString *)numberStr
{
    self.intputTextFeild.text  = [self.intputTextFeild.text stringByAppendingString:numberStr];
    //增加号码
    self.deleteBtn.hidden = NO;
    //刷新数据
    [self reloadDataWithNumber:self.intputTextFeild.text];
    
}

#pragma mark -- TextFied Delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@" "]) {
        return NO;
    }
    NSLog(@"(%lu,%lu)  , %@  and %@",(unsigned long)range.location,(unsigned long)range.length,textField.text,string);
    //如果是清空 则恢复原数据
    if (range.location == 0 && range.length==1)
    {
#warning 刷新表格数据
        [self.tableView reloadData];
        
        self.deleteBtn.hidden = YES;
        self.keyboardBottomBar.phoneCallBtnHidden = YES;
        
    }else
    {
        self.deleteBtn.hidden = NO;
        self.keyboardBottomBar.phoneCallBtnHidden = NO;
        
        NSString* searchStr = @"";
        //增加
        if (range.location==textField.text.length) {
            searchStr = [textField.text stringByAppendingString:string];
        }
        //减少
        else
        {
            searchStr = [textField.text stringByReplacingCharactersInRange:range withString:@""];
        }
        //刷新数据
        [self reloadDataWithNumber:searchStr];
        
    }
    return YES;
}

- (void)reloadDataWithNumber:(NSString *)numberString
{
#warning 刷新表格数据
    [self.tableView reloadData];
}

#pragma mark -- UISearchBarDelegate, UISearchDisplayDelegate
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    _isSearchNow = YES;
    
    [self phoneNumViewShow:NO];
    return YES;
}

-(void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
    _isSearchNow = NO;
    [self phoneNumViewShow:YES];
}






@end
